//
//  JNCardSDKRepayPlanVC.m
//  IDCardManager
//
//  Created by 金牛 on 2017/7/25.
//  Copyright © 2017年 zou. All rights reserved.
//

#import "JNCardSDKRepayPlanVC.h"
#import "JNCardSDKRepayPlanCell.h"
#import "JNCardSDKNewRepayPlanVC.h"
#import "JNCardSDKCardCellModel.h"
#import "JNCardSDKCardDetailVC.h"
#import "SWAlertController.h"
#import "JNCardSDKFVRepayPlanDetailVC.h"
@interface JNCardSDKRepayPlanVC ()<UITableViewDataSource,UITableViewDelegate>
{
    UILabel * _balanceLab , *_btnBankLab;
    NSMutableArray * _dataArr,*_invalidArray/*已作废列表的数组*/,* _validArray,*_allPlayDataArr,*_allPlayDataArr1;
    NSInteger _page;
    NSString * _foldBtnTitle,*_selectCardID,*_shouldPayMoney,*_planTime,*_restartPlayID,*_cardPlayIDForCancel;
    BOOL _isFoldCell, _requestAll/*从卡片详情点进来的，点查看全部的请求所有内容*/,_isNewCancelBtnClick;
    UIImageView * _btnBankImgView;
    UIButton * _choseBtn;
    NSMutableArray * _userBankCardArr,*_userCreditCardIDArr;
}
@property(nonatomic,retain)UITableView * myTab;
@property(nonatomic,retain)UIView * choseBankBGView;
@property(nonatomic,retain)UIView * AllBgView;
@property(nonatomic,retain)UIView * shelterView;
@end

@implementation JNCardSDKRepayPlanVC

- (void)viewDidLoad {
    [super viewDidLoad];
    self.view.backgroundColor = [UIColor colorWithHue:0 saturation:0 brightness:0.96 alpha:1];
    self.myTitle = @"还款计划";
    _page = 1;
    _isFoldCell = YES;//默认是折叠的
    _isNewCancelBtnClick = NO;
    _requestAll = self.userCreditCardId.length>0?NO: YES;
    _userBankCardArr = [NSMutableArray new];
    _userCreditCardIDArr = [NSMutableArray new];
    _dataArr = [NSMutableArray new];
    _allPlayDataArr = [NSMutableArray new];
    _allPlayDataArr1 = [NSMutableArray new];
    [self.view addSubview:self.AllBgView];
    [self.view addSubview:self.myTab];
    
}
-(void)viewWillAppear:(BOOL)animated{
    [self getstart];
}
-(void)getstart{
    self->_page = 1;
    [self requestPayPlanList];
}
-(void)requestPayPlanList{//用于查全部的接口
    [JNCardSDKReuserFile getUserAllPlanWithPage:_page andBackBlock:^(NSDictionary *backDic) {
        if ([backDic[@"status"]isEqualToString:@"1"]) {
            NSArray * dataArr = backDic[@"data"];
            if (self->_page == 1) {
                [self->_allPlayDataArr removeAllObjects];
                [self->_dataArr removeAllObjects];
                [self->_invalidArray removeAllObjects];
                [self->_validArray removeAllObjects];
            }
            [self->_allPlayDataArr addObjectsFromArray:dataArr];
            if (dataArr.count>0) {
                if (self.userCreditCardId.length>0) {//表示从往期计划点击来的
                    if (self->_requestAll == YES) {
                        [self splitDataToInvalidDataAndValidData:dataArr];
                    }else{
                        NSMutableArray * tmpArr = [NSMutableArray new];
                        for (NSDictionary * dic  in dataArr) {
                            if ([self.userCreditCardId isEqualToString:dic[@"userCreditCardId"]]) {
                                [tmpArr addObject:dic];
                            }
                        }
                        if (tmpArr.count!=0) {
                            [self->_userBankCardArr addObject:dataArr[0]];
                        }
                        self->_selectCardID = self.userCreditCardId;
                        [self requestSelectPlanList];
                    }
                    [self requestBankCardInfo];
                }else{
                    [self splitDataToInvalidDataAndValidData:dataArr];
                    if (self->_userBankCardArr.count==0) {
                        [self requestBankCardInfo];
                    }
                }
            }
            [self->_myTab.mj_header endRefreshing];
            [self->_myTab.mj_footer endRefreshing];
            if (self->_allPlayDataArr.count==[backDic[@"count"] integerValue]) {
                [self->_myTab.mj_footer endRefreshingWithNoMoreData];
            }
            [self->_myTab reloadData];
        }else{
            [self->_myTab.mj_header endRefreshing];
            [self->_myTab.mj_footer endRefreshing];
            [SVProgressHUD dismiss];
            [JNCardSDKMytools warnText:backDic[@"msg"] status:JNCardSDKError];
        }
    }];
}
-(void)requestSelectPlanList{
    [SVProgressHUD show];
    NSMutableDictionary * p = [JNCardSDKReuserFile returnHYKBaseDic];
    [p setObject:_selectCardID forKey:@"userCreditCardId"];
    [p setObject:@"10" forKey:@"pagelimit"];
    [p setObject:[NSString stringWithFormat:@"%ld",_page] forKey:@"currentpage"];
    NSString *utf = [JNCardSDKWorkUrl returnURL:Interface_For_GetCardPlanlist];
    [PGNetworkHelper GET:utf parameters:p cache:NO responseCache:nil success:^(id responseObject) {
        if ([responseObject[@"status"]isEqualToString:@"1"]) {
            [SVProgressHUD dismiss];
            if (self->_page==1) {
                [self->_allPlayDataArr1 removeAllObjects];
            }
            NSArray * dataArr = responseObject[@"data"];
            [self->_allPlayDataArr1 addObjectsFromArray:dataArr];
            if (dataArr.count == 0) {
                [self.myTab showNoView:@"暂无数据" image:nil certer:CGPointZero];
            }else{
                [self splitDataToInvalidDataAndValidData:dataArr];
            }
            [self->_myTab.mj_header endRefreshing];
            [self->_myTab.mj_footer endRefreshing];
            if (self->_allPlayDataArr1.count==[responseObject[@"count"] integerValue]) {
                [self->_myTab.mj_footer endRefreshingWithNoMoreData];
            }
            [self->_myTab reloadData];
        }else{
            [self->_myTab.mj_header endRefreshing];
            [self->_myTab.mj_footer endRefreshing];
            [SVProgressHUD dismiss];
            [JNCardSDKMytools warnText:responseObject[@"msg"] status:JNCardSDKError];
        }
    } failure:^(NSError *error) {
    }];
}
-(void)requestBankCardInfo{
    NSMutableDictionary * p = [JNCardSDKReuserFile returnHYKBaseDic];
    [p setObject:@"30" forKey:@"pagelimit"];
    [p setObject:[NSString stringWithFormat:@"%ld",_page] forKey:@"currentpage"];
    NSString *utf = [JNCardSDKWorkUrl returnURL:Interface_For_GetUserBankList];
    [PGNetworkHelper GET:utf parameters:p cache:NO responseCache:nil success:^(id responseObject) {
        [SVProgressHUD dismiss];
        if ([responseObject[@"status"]isEqualToString:@"1"]) {
            [self->_userBankCardArr removeAllObjects];
            NSArray * arr = responseObject[@"data"];
            [self->_userBankCardArr addObjectsFromArray:arr];
        }else{
            [JNCardSDKMytools warnText:responseObject[@"msg"] status:JNCardSDKError];
        }
    } failure:^(NSError *error) {
        
    }];
}
#pragma mark 懒加载
-(UITableView*)myTab{
    if (_myTab == nil) {
        _myTab = [[UITableView alloc]initWithFrame:Frame(0, kTopHeight+64, IPHONE_WIDTH, IPHONE_HEIGHT - kTopHeight-64)];
        _myTab.delegate = self;
        _myTab.dataSource = self;
        [_myTab setSeparatorStyle:UITableViewCellSeparatorStyleNone];
        _myTab.separatorStyle = UITableViewCellSeparatorStyleNone;
        _myTab.mj_header = [MJRefreshNormalHeader headerWithRefreshingBlock:^{
            self->_page = 1;
            [self requestPayPlanList];
        }];
        _myTab.mj_footer = [MJRefreshBackNormalFooter footerWithRefreshingBlock:^{
            self->_page ++;
            if (self->_selectCardID.length > 0 ) {
                [self requestSelectPlanList];
            }else{
                [self requestPayPlanList];
            }
        }];
    }
    return _myTab;
}
-(UIView*)choseBankBGView{
    if (_choseBankBGView == nil) {
        CGFloat btnHight = 44;
        CGFloat imageViewHeight = 25;
        NSInteger tmpCount = _userBankCardArr.count+1;
        _choseBankBGView = [[UIView alloc]initWithFrame:Frame(AUTO(10), 128-AUTO(10), IPHONE_WIDTH*0.9, tmpCount*btnHight)];
        _choseBankBGView.layer.borderWidth = 0.5;
        _choseBankBGView.layer.borderColor = [UIColor colorWithHue:0 saturation:0 brightness:0.93 alpha:1].CGColor;
        _choseBankBGView.backgroundColor = [UIColor whiteColor];
        for (int i = 0; i<tmpCount; i++) {
            UIButton * btn = [[UIButton alloc]initWithFrame:Frame(0, i*btnHight, IPHONE_WIDTH*0.9, btnHight)];
            btn.tag = 700+i;
            btn.layer.borderColor = [UIColor colorWithHue:0 saturation:0 brightness:0.93 alpha:1].CGColor;
            btn.layer.borderWidth = 0.5;
            [btn addTarget:self action:@selector(choseOneBankBtnClick:) forControlEvents:UIControlEventTouchUpInside];
            [_choseBankBGView addSubview:btn];
            UIImageView * bankView = [[UIImageView alloc]initWithFrame:Frame(AUTO(5), (btnHight-imageViewHeight)/2, imageViewHeight, imageViewHeight)];
            bankView.tag = 800+i;
            [btn addSubview:bankView];
            UILabel * lab = [[UILabel alloc]initWithFrame:Frame(CGRectGetMaxX(bankView.frame)+10, (btnHight-imageViewHeight)/2, CGRectGetWidth(btn.frame)-AUTO(40), imageViewHeight)];
            lab.font = [UIFont systemFontOfSize:15];
            lab.tag = 900+i;
            [btn addSubview:lab];
            if (i==0) {
                bankView.image = Image(@"全部");
                lab.text = @"全部还款计划";
            }else{
                NSDictionary * dic = _userBankCardArr[i-1];
                [bankView sd_setImageWithURL:[NSURL URLWithString:[NSString stringWithFormat:@"%@%@",JNCardSDKImageDomain,dic[@"bankImg"]]]];
                lab.text = [NSString stringWithFormat:@"%@ %@",dic[@"bankName"],dic[@"bankNum"]];
            }
        }
    }
    return _choseBankBGView;
}
-(UIView*)AllBgView{
    if (_AllBgView == nil) {
        CGFloat imageViewHeight = 25;
        _AllBgView = [[UIView alloc]initWithFrame:Frame(0, kTopHeight, IPHONE_WIDTH, kTopHeight)];
        _AllBgView.backgroundColor = [UIColor whiteColor];
        [self.view addSubview:_AllBgView];
        _choseBtn = [UIButton new];
        _choseBtn.clipsToBounds = YES;
        _choseBtn.layer.borderColor = [UIColor colorWithHue:0 saturation:0 brightness:0.93 alpha:1].CGColor;
        _choseBtn.layer.borderWidth = 0.5;
        _choseBtn.selected = NO;
        [_choseBtn addTarget:self action:@selector(choseBankPlanBtnClick:) forControlEvents:UIControlEventTouchUpInside];
        [_AllBgView addSubview:_choseBtn];
        _choseBtn.sd_layout.leftSpaceToView(_AllBgView, AUTO(10)).topSpaceToView(_AllBgView, AUTO(10)).bottomSpaceToView(_AllBgView, AUTO(10)).widthIs(0.9*IPHONE_WIDTH);
        
        _btnBankImgView = [UIImageView new];
        
        [_choseBtn addSubview:_btnBankImgView];
        _btnBankImgView.sd_layout.leftSpaceToView(_choseBtn, AUTO(5)).centerYEqualToView(_choseBtn).widthIs(imageViewHeight).heightIs(imageViewHeight);
        
        _btnBankLab = [UILabel new];
        _btnBankLab.font = [UIFont systemFontOfSize:15];
        
        [_choseBtn addSubview:_btnBankLab];
        _btnBankLab.sd_layout.leftSpaceToView(_btnBankImgView, 10).centerYEqualToView(_btnBankImgView).heightIs(imageViewHeight);
        [_btnBankLab setSingleLineAutoResizeWithMaxWidth:IPHONE_WIDTH*0.8];
        if (self.userCreditCardId.length>0) {//表示从卡片信息进来的
            [_btnBankImgView sd_setImageWithURL:[NSURL URLWithString:[NSString stringWithFormat:@"%@%@",JNCardSDKImageDomain,self.cardModel.bankImg]]];
            _btnBankLab.text = [NSString stringWithFormat:@"%@ %@",self.cardModel.bankName,self.cardModel.bankNum];
        }else{
            _btnBankImgView.image = Image(@"全部");
            _btnBankLab.text = @"全部还款计划";
        }
    }
    return _AllBgView;
}

#pragma mark 事件触发
-(void)choseBankPlanBtnClick:(UIButton *)sender{
    sender.selected = !sender.selected;
    if (sender.selected == YES) {
        //        [self.view addSubview:self.shelterView];
        [self.view addSubview:self.AllBgView];
        [self.view addSubview:self.choseBankBGView];
    }else{
        [_choseBankBGView removeFromSuperview];
        _choseBankBGView = nil;
    }
}
-(void)choseOneBankBtnClick:(UIButton*)sender{
    _page = 1;
    [_invalidArray removeAllObjects];
    [_validArray removeAllObjects];
    [_dataArr removeAllObjects];
    UILabel * lab = [_choseBankBGView viewWithTag:900+sender.tag-700];
    _btnBankLab.text = lab.text;
    UIImageView * imgView = [_choseBankBGView viewWithTag:800+sender.tag-700];
    _btnBankImgView.image = imgView.image;
    //从array中获取银行的信息然后把信息设置到展示按钮中
    _choseBtn.selected = !_choseBtn.selected;
    [_choseBankBGView removeFromSuperview];
    _choseBankBGView = nil;
    if (sender.tag==700) {
        [_userBankCardArr removeAllObjects];
        [self requestPayPlanList];
        _requestAll = YES;
        _selectCardID = @"";
    }else{
        _requestAll = NO;
        NSDictionary * dic = _userBankCardArr[sender.tag -701];
        _selectCardID = dic[@"userCreditCardId"];
        
        [self requestSelectPlanList];
    }
}
#pragma mark tableView代理
-(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
    return _dataArr.count;
}
-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    if (section==_dataArr.count-1) {
        //过期的那个区
        if (_isFoldCell == YES) {
            return 0;
        }else{
            NSArray * arr = _dataArr[section];
            return arr.count;
        }
    }else{
        NSArray * arr = _dataArr[section];
        return arr.count;
    }
}
-(UITableViewCell*)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    JNCardSDKRepayPlanCell * cell = nil;
    if (!cell) {
        cell = [[JNCardSDKRepayPlanCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@"cell"];
        JNCardSDKRepayPlanCellModel * model = _dataArr[indexPath.section][indexPath.row];
        cell.model = model;
        //2018-8-22删除cell底部的按钮的block，改功能废弃在2018-5-5
    }
    return cell;
}
-(CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section{
    return 0.001;
}
-(CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section{
    if (section == 0) {
        return 44;
    }else{
        return 0.01;
    }
}
-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    if (IPHONE_WIDTH==320) {
        return AUTO(186);
    }
    return 130;
}
- (CGFloat)cellContentViewWith
{
    CGFloat width = [UIScreen mainScreen].bounds.size.width;
    // 适配ios7横屏
    if ([UIApplication sharedApplication].statusBarOrientation != UIInterfaceOrientationPortrait && [[UIDevice currentDevice].systemVersion floatValue] < 8) {
        width = [UIScreen mainScreen].bounds.size.height;
    }
    return width;
}
-(UIView *)tableView:(UITableView *)tableView viewForFooterInSection:(NSInteger)section{
    if (section ==0) {
        UIView * view = [UIView new];
        UIButton * btn = [UIButton new];
        if (_foldBtnTitle.length == 0) {
            [btn setTitle:@"------  点击查看往期记录 ------" forState:0];
        }else{
            [btn setTitle:_foldBtnTitle forState:0];
        }
        btn.titleLabel.font = Font(17);
        [btn setTitleColor:[UIColor blackColor] forState:0];
        [btn addTarget:self action:@selector(viewInvalidRecord:) forControlEvents:UIControlEventTouchUpInside];
        btn.selected = NO;
        [view addSubview:btn];
        btn.sd_layout.leftEqualToView(view).rightEqualToView(view).topEqualToView(view).bottomEqualToView(view);
        return view;
    }else{
        return nil;
    }
    
}
-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    JNCardSDKRepayPlanCellModel * model = self->_dataArr[indexPath.section][indexPath.row];
    if ([model.theState isEqualToString:@"5"]||[model.theState isEqualToString:@"6"]||[model.theState isEqualToString:@"2"]) {
        JNCardSDKFVRepayPlanDetailVC * vc = [JNCardSDKFVRepayPlanDetailVC new];
        vc.myTitle = @"计划详情";
        vc.planInfoDic = model.mj_keyValues;
        vc.planID = model.userRepayPlayId;
        vc.isFromRepayList = YES;
        [self.navigationController pushViewController:vc animated:YES];
    }else{
        JNCardSDKCardDetailVC * vc = [JNCardSDKCardDetailVC new];
        vc.userCreditCardId = model.userCreditCardId;
        vc.myTitle = model.bankName;
        [self.navigationController pushViewController:vc animated:YES];
    }
}

#pragma mark 折叠展开过往记录
-(void)viewInvalidRecord:(UIButton*)sender{
    sender.selected = !sender.selected;
    if ([_foldBtnTitle isEqualToString:@"------  点击收起往期记录 ------"]) {
        _foldBtnTitle = @"------  点击查看往期记录 ------";
    }else{
        _foldBtnTitle = @"------  点击收起往期记录 ------";
    }
    [sender setTitle:_foldBtnTitle forState:0];
    _isFoldCell = !_isFoldCell;
    
    if (_dataArr.count>0) {
        NSIndexSet *indexSet=[[NSIndexSet alloc]initWithIndex:1];
        [_myTab reloadSections:indexSet withRowAnimation:UITableViewRowAnimationAutomatic];
    }
}

//将data数据分成过期和未过期两部分
-(void)splitDataToInvalidDataAndValidData:(NSArray *)dataArr{
    NSMutableArray * array = [NSMutableArray new];
    NSMutableArray * appArr = [NSMutableArray new];
    if (_invalidArray == nil) {
        _validArray = [NSMutableArray new];
        _invalidArray = [NSMutableArray new];
    }
    for (NSDictionary * dic  in dataArr) {
        
        if ([dic[@"theState"] intValue]==1) {
            [appArr addObject:dic];
        }else if ([dic[@"theState"] intValue]==-1){
            
        }else{
            [array addObject:dic];
        }
    }
    if (appArr.count>0) {
        NSMutableArray * arrM = [NSMutableArray arrayWithArray:[JNCardSDKRepayPlanCellModel mj_objectArrayWithKeyValuesArray:appArr]];
        [_validArray addObjectsFromArray:arrM];
    }
    if (array.count>0) {
        NSMutableArray * arrMp = [NSMutableArray arrayWithArray:[JNCardSDKRepayPlanCellModel mj_objectArrayWithKeyValuesArray:array]];
        [_invalidArray addObjectsFromArray:arrMp];
    }
    
    if (_dataArr.count == 0) {
        [_dataArr addObject:_validArray];
        [_dataArr addObject:_invalidArray];
    }else{
        [_dataArr replaceObjectAtIndex:0 withObject:_validArray];
        [_dataArr replaceObjectAtIndex:1 withObject:_invalidArray];
    }
}
-(UIView*)shelterView{
    if (_shelterView == nil) {
        _shelterView = [[UIView alloc]initWithFrame:Frame(0, 0, IPHONE_WIDTH, IPHONE_HEIGHT)];
        _shelterView.backgroundColor = [UIColor colorWithWhite:0 alpha:0.5];
        UITapGestureRecognizer * tap = [[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(tapClick)];
        [_shelterView addGestureRecognizer:tap];
    }
    return _shelterView;
}
-(void)tapClick{
    [_shelterView removeFromSuperview];
    _shelterView = nil;
    //    [self.view addSubview:self.AllBgView];
}
//获取信用卡计划列表,因为修改计划要传一个计划本金，这里没有这个参数
-(void)getUserCardPlanListRequest:(JNCardSDKRepayPlanCellModel*)planModel{
    [JNCardSDKReuserFile getUserCardPlanListRequest:planModel andBackBlock:^(NSDictionary *backDic) {
        NSArray * dataArr = backDic[@"data"];
        if (dataArr.count!=0) {
            NSMutableArray * arrM = [NSMutableArray arrayWithArray:[JNCardSDKCardCellModel mj_objectArrayWithKeyValuesArray:(NSArray*)backDic[@"data"]]];
            dispatch_async(dispatch_get_main_queue(), ^{
                JNCardSDKNewRepayPlanVC * vc = [JNCardSDKNewRepayPlanVC new];
                JNCardSDKCardCellModel * cllmODEL = arrM[0];
                vc.cardInfoModel = cllmODEL;
                vc.repayPlayId = cllmODEL.userRepayPlayId;
                vc.myTitle = @"修改还款计划";
                vc.myPlanType = 2;//原本的ModifyPlanVC弃用，使用type在新增信用卡判断是修改还是新增
                [self.navigationController pushViewController:vc animated:YES];
            });
        }
    }];
}
-(void)sendResetRequest{
    [SVProgressHUD show];
    NSMutableDictionary * paraDic = [JNCardSDKReuserFile returnHYKBaseDic];
    NSString * url = [JNCardSDKWorkUrl returnURL:Interface_For_CancelCardState];

    [paraDic setObject:_restartPlayID forKey:@"PlanId"];
    [paraDic setObject:@"1" forKey:@"TheState"];//重启计划
    [paraDic setObject:@"2" forKey:@"NewType"];
    [JNCardSDKMytools requestStringByPostUrl:url parameter:paraDic success:^(NSDictionary *backDic) {
        [SVProgressHUD dismiss];
        if ([backDic[@"status"]isEqualToString:@"1"]) {
            [JNCardSDKMytools warnText:@"重启成功" status:JNCardSDKSuccess];
            [self->_shelterView removeFromSuperview];
            self->_shelterView = nil;
            [self->_invalidArray removeAllObjects];
            [self->_validArray removeAllObjects];
            [self->_dataArr removeAllObjects];
            [self requestPayPlanList];
        }else{
            [JNCardSDKMytools warnText:backDic[@"msg"] status:JNCardSDKError];
        }
    } fail:^(NSError *error) {
        
    }];
}

@end

